import { useEffect } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import { handleLocalUserInfo } from '@/utils/utils'
import { userinfo } from '@/store'
import { useRecoilState } from 'recoil'

export const useCheckLogin = () => {
  const { pathname } = useLocation()
  const navigate = useNavigate()
  const { getUserToken } = handleLocalUserInfo()
  const userToken = getUserToken()
  const skipLoginRputes = ['/login', '/']
  useEffect(() => {
    if (!skipLoginRputes.includes(pathname) && !userToken?.token) {
      navigate('/login', { replace: true })
    }
  }, [])
}

export const useUserInfo = () => {
  const [user, setUser] = useRecoilState(userinfo)
  return {
    user,
    setUser,
  }
}

const enSpecialData = (obj) => {
  const newObj = {}
  if (obj && typeof obj === 'object') {
    Object.keys(obj).forEach((item) => {
      const value = obj[item]
      if (value && typeof value === 'object') {
        if (value instanceof Date) {
          newObj[item] = {
            __dateType: 'date',
            value: value.toISOString(),
          }
        } else {
          newObj[item] = enSpecialData(value)
        }
      } else {
        newObj[item] = value
      }
    })
  }
  return newObj
}

const deSpecialData = (obj) => {
  const newObj = {}
  if (obj && typeof obj === 'object') {
    Object.keys(obj).forEach((item) => {
      const value = obj[item]
      if (value && typeof value === 'object') {
        if (value.__dateType && value.__dateType === 'date') {
          newObj[item] = new Date(value.value)
        } else {
          newObj[item] = deSpecialData(value)
        }
      } else {
        newObj[item] = value
      }
    })
  }
  return newObj
}

// 会话数据存储
export const useCacheSessionData = (key) => {
  const setSessionData = (data) => {
    sessionStorage.setItem(key, JSON.stringify(enSpecialData(data)))
  }
  let data = sessionStorage.getItem(key)
  if (data) {
    data = deSpecialData(JSON.parse(data))
  }
  const clear = () => sessionStorage.removeItem(key)
  return [data, setSessionData, clear]
}
